package dimensional.traveler.client.screens.characterclasschooser;

import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.logical.shared.AttachEvent;
import com.google.gwt.event.logical.shared.AttachEvent.Handler;
import com.google.gwt.user.client.rpc.AsyncCallback;

import dimensional.traveler.client.UserManagement;
import dimensional.traveler.client.mvc.MediatedController;
import dimensional.traveler.client.services.CharacterClassService;
import dimensional.traveler.client.services.CharacterClassServiceAsync;
import dimensional.traveler.client.services.MissionService;
import dimensional.traveler.client.services.MissionServiceAsync;
import dimensional.traveler.client.ui.util.LoadingBar;
import dimensional.traveler.shared.model.CharacterClassDTO;
import dimensional.traveler.shared.model.missionSequence.MissionSequence;

public class CharacterClassChooserController extends MediatedController implements Handler {

	private CharacterClassChooserScreen screen;
	private CharacterClassServiceAsync characterClassService = GWT.create(CharacterClassService.class);
	private MissionServiceAsync missionService = GWT.create(MissionService.class);
	
	public void back() {
		mediator.displayWelcomeScreen();
	}

	public void startTutorial(String selectedCharacterId) {
		missionService.setCharacterClassId(UserManagement.getLoggedInUser(), selectedCharacterId, new AsyncCallback<MissionSequence>() {
			
			@Override
			public void onSuccess(MissionSequence result) {
				mediator.displayMissionSequence(result);
			}
			
			@Override
			public void onFailure(Throwable caught) {
				handleRequestFailure(caught);
			}
		});
	}

	@Override
	public void onAttachOrDetach(AttachEvent event) {
		screen = (CharacterClassChooserScreen) event.getSource();
		if (event.isAttached()){
			requestCharacterClasses();
		}
	}

	private void requestCharacterClasses() {
		LoadingBar.showLoadingBar();
		
		characterClassService.getCharacterClasses(new AsyncCallback<List<CharacterClassDTO>>() {
			
			@Override
			public void onSuccess(List<CharacterClassDTO> characterClasses) {
				LoadingBar.hideLoadingBar();
				screen.addCharacterClasses(characterClasses);
			}
			
			@Override
			public void onFailure(Throwable caught) {
				handleRequestFailure(caught);
			}
		});
		
	}

}
